import util from '../../../utils/util.js';
import api from '../../../config/api.js';
import user from '../../../services/user.js';
const app = getApp();

Page({
  data: {
    userInfo: {},
    showLoginDialog: false
  },
  onLoad(options) {
    // 页面初始化 options为页面跳转所带来的参数
  },
  onReady() {

  },
  onShow() {
    this.setData({
      userInfo: app.globalData.userInfo,
    });
  },
  onHide() {
    // 页面隐藏

  },
  onUnload() {
    // 页面关闭
  },

  onUserInfoClick() {
    if (my.getStorageSync({key:'token'}).data) {

    } else {
      this.showLoginDialog();
    }
  },

  showLoginDialog() {
    this.setData({
      showLoginDialog: true
    })
  },

  onCloseLoginDialog () {
    this.setData({
      showLoginDialog: false
    })
  },

  onDialogBody () {
    // 阻止冒泡
  },

  onWechatLogin(e) {
    let code = null;
    util.login().then((res) => {
      code = res;
      return util.getUserInfo();
    }).then((userInfo) => {
      return util.request(api.AuthLoginByWeixin, {
        code: code,
        userInfo: userInfo,
        vendor: 'alipay'
      }, 'POST');
    }).then((res) => {
      console.log(res)
      if (res.errno !== 0) {
        my.showToast({
          content: '微信登录失败',
        })
        return false;
      }
      // 设置用户信息
      this.setData({
        userInfo: res.data.userInfo,
        showLoginDialog: false
      });
      app.globalData.userInfo = res.data.userInfo;
      app.globalData.token = res.data.token;
      my.setStorageSync({key:'userInfo',data:JSON.stringify(res.data.userInfo)});
      my.setStorageSync({key:'token',data:res.data.token});
    }).catch((err) => {
      console.log(err)
    })
  },

  onOrderInfoClick(event) {
    my.navigateTo({
      url: '/pages/ucenter/order/order',
    })
  },

  onSectionItemClick(event) {

  },

  // TODO 移到个人信息页面
  exitLogin() {
    my.confirm({
      title: '',
      confirmColor: '#b4282d',
      content: '退出登录？',
      success(res) {
        if (res.confirm) {
          my.removeStorageSync({key:'token'});
          my.removeStorageSync({key:'userInfo'});
          my.switchTab({
            url: '/pages/index/index'
          });
        }
      }
    })

  }
})